'use strict';



const Service = require('egg').Service;

class TagService extends Service {
    async add({name,uid}){
       const {ctx,app} = this;
       const count = await ctx.model.Tag.find({}).count();
       if(count > app.const.tagMax){
         return Promise.reject(app.resCode.tagMax);
       }
       const res = await ctx.model.Tag.findOne({name,uid});
       if(res){
            return Promise.reject(app.resCode.tagRepet);
       }else{
        var config = new ctx.model.Tag({name,uid});
        return config.save();  
       }
    }
    async remove(id){
        console.log(this.ctx.model.Tag.removeOne,this.ctx.model.Tag.remove)
        return this.ctx.model.Tag.deleteOne({"_id":id});
    }
    async update({id,name,uid}){
        const {ctx,app} = this;
        const res = await ctx.model.Tag.findOne({uid,name});
        if(res && res._id == id){
            return Promise.reject(app.resCode.tagRepet);
        }else{
            //更新所有的note
            await ctx.model.Note.updateMany({"uid":uid,"tagId":id},{"$set":{"tagName":name}});
        }
        return this.ctx.model.Tag.updateOne({"_id":id},{"$set":{name}});
    }
    async list(uid){
        return this.ctx.model.Tag.find({uid});
    }
    async info(id){
        return this.ctx.model.Tag.findOne({"_id":id});
    }
}

module.exports = TagService;